using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EventManager : MonoBehaviour
{

    private static EventManager _manager = new EventManager();
    private EventManager()
    {
    }

    public static EventManager getInstance()
    {
        return _manager;
    }

    private Dictionary<int, List<Action<BaseEvent>>> actions = new Dictionary<int, List<Action<BaseEvent>>>();

    public void register(int eventId, Action<BaseEvent> action)
    {
        List<Action<BaseEvent>> ac;
        if (actions.TryGetValue(eventId, out ac))
        {
            if (ac.Contains(action))
            {
                return;
            }
            
        }
        else
        {
            ac = new List<Action<BaseEvent>>();
            actions.Add(eventId,ac);
        }
        ac.Add(action);
    }
    
    public void remove(int eventId, Action<BaseEvent> action)
    {
        List<Action<BaseEvent>> ac;
        if (actions.TryGetValue(eventId, out ac))
        {
            ac.Remove(action);
        }
    }

    public void dispatcher(BaseEvent baseEvent)
    {
        List<Action<BaseEvent>> ac;
        if (actions.TryGetValue(baseEvent.eventId, out ac))
        {
            foreach (Action<BaseEvent> action in ac)
            {
                try
                {
                    action.Invoke(baseEvent);
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
            }
        }
    }
}
